﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace linkouqs.Gamekit {

    public abstract class PushableObject : MonoBehaviour {

        /// <summary>
        /// 被推动时需要播放的音效
        /// </summary>
        public AudioClip soundFX;

        /// <summary>
        /// 当该物品被角色推动时 角色要减少的速度的百分比 0.5代表减少50%
        /// </summary>
        [Range(0, 0.9f)]
        public float slowDown = 0.5f;

        /// <summary>
        /// 该物品是否正在被角色推动
        /// </summary>
        public bool IsPushing {
            get {
                return Owner != null;
            }
        }

        public CharacterAbilityPush Owner {
            get;
            protected set;
        }

        protected float m_OldSpeed;

        protected List<CharacterAbilityPush> m_Users = new List<CharacterAbilityPush>();

        public GameObject trigger;

        protected virtual void Awake() {

            var listener = Physical2DEventLinstener.Get(trigger);
            listener.onTriggerEnter2D = go => {

                CharacterAbilityPush user = go.GetComponent<CharacterAbilityPush>();
                if (user == null) {
                    return;
                }
                if (m_Users.Contains(user)) {
                    return;
                }
                m_Users.Add(user);
                user.OnSelect(this);
            };
            listener.onTriggerExit2D = go => {

                CharacterAbilityPush user = go.GetComponent<CharacterAbilityPush>();
                if (user == null) {
                    return;
                }
                if (m_Users.Contains(user)) {
                    m_Users.Remove(user);
                }
                user.OnUnselect(this);
            };

        }

        public virtual bool CanPush(CharacterAbilityPush user) {
            if (IsPushing) {
                return false;
            }
            if (!m_Users.Contains(user)) {
                return false;
            }
            return user.Character.IsFaceTo(transform);
        }

        public virtual void OnStartPush(CharacterAbilityPush user) {
            Owner = user;
            m_OldSpeed = Owner.Character.runSpeed;
            Owner.Character.runSpeed = m_OldSpeed * (1f - slowDown);
        }

        public virtual void OnStopPush() {
            if(Owner == null) {
                return;
            }
            Owner.Character.runSpeed = m_OldSpeed;
            Owner.Character.CharacterInput.ResetHorizontal();
            Owner = null;
        }

    }


}

